package com.ruoyi.asms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.ams.controller.AmsAssetTypeController;
import com.ruoyi.asms.domain.AsmsFaultAssetReason;
import com.ruoyi.asms.domain.vo.AsmsFaultAssetReasonAddVo;
import com.ruoyi.asms.domain.vo.AsmsFaultAssetReasonEditVo;
import com.ruoyi.asms.service.IAsmsFaultAssetReasonService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.AmsAssetType;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.security.annotation.PreAuthorize;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 资产故障原因Controller
 *
 * @author yfkj
 * @date 2021-10-21
 */
@RestController
@RequestMapping("/asms/AsmsFaultAssetReason")
public class AsmsFaultAssetReasonController extends BaseController {
    @Autowired
    private IAsmsFaultAssetReasonService asmsFaultAssetReasonService;
//    @Autowired
//    private RemoteAssetTypeService remoteAssetTypeService;

    @Autowired
    private AmsAssetTypeController assetTypeController;

    /**
     * 查询资产故障原因列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsFaultAssetReason:list")
    @GetMapping("/list")
    @ApiOperation("根据分类id或查询条件获取类型的故障原因列表")
    public TableDataInfo list(AsmsFaultAssetReason asmsFaultAssetReason) {
        R<AmsAssetType> rTypeInfo = assetTypeController. getInfo(asmsFaultAssetReason.getAssetTypeId());
        if (R.FAIL == rTypeInfo.getCode()) {
            throw new ServiceException(rTypeInfo.getMsg());
        }
        Set<String> reason = new HashSet<>();
        QueryWrapper<AsmsFaultAssetReason> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(asmsFaultAssetReason.getFaultReason())) {
            wrapper.like(AsmsFaultAssetReason.FAULT_REASON, asmsFaultAssetReason.getFaultReason());
        }
        if (StringUtils.isNotEmpty(asmsFaultAssetReason.getSolution())) {
            wrapper.like(AsmsFaultAssetReason.SOLUTION, asmsFaultAssetReason.getSolution());
        }
        if (asmsFaultAssetReason.getStatus() != null) {
            wrapper.eq(AsmsFaultAssetReason.STATUS, asmsFaultAssetReason.getStatus());
        }
        startPage();
        List<AsmsFaultAssetReason> reasons = new ArrayList<>();
        String typeIdString = rTypeInfo.getData().getAncestors() + "," + asmsFaultAssetReason.getAssetTypeId();
        for (Long typeId : Convert.toLongArray(typeIdString)) {
            if (!typeId.equals(0L)) {
                wrapper.eq(AsmsFaultAssetReason.ASSET_TYPE_ID, typeId);
                List<AsmsFaultAssetReason> lst = asmsFaultAssetReasonService.list(wrapper);
                for (AsmsFaultAssetReason assetReason : lst) {
                    if (!reason.contains(assetReason.getFaultReason())) {
                        reason.add(assetReason.getFaultReason());
                        reasons.add(assetReason);
                    }
                }
            }
        }
        return getDataTable(reasons);
    }

    /**
     * 导出资产故障原因列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsFaultAssetReason:export")
    @Log(title = "资产故障原因", businessType = BusinessType.EXPORT)
    @PostMapping(value="/export", produces = "application/octet-stream")
    public void export(HttpServletResponse response, AsmsFaultAssetReason asmsFaultAssetReason) throws IOException {
        List<AsmsFaultAssetReason> list = asmsFaultAssetReasonService.selectAsmsFaultAssetReasonList(asmsFaultAssetReason);
        ExcelUtil<AsmsFaultAssetReason> util = new ExcelUtil<AsmsFaultAssetReason>(AsmsFaultAssetReason.class);
        util.exportExcel(response, list, "资产故障原因数据");
    }

    /**
     * 获取资产故障原因详细信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsFaultAssetReason:query")
    @GetMapping(value = "/{faultAssetReasonId}")
    public AjaxResult getInfo(@PathVariable("faultAssetReasonId") Long faultAssetReasonId) {
        return AjaxResult.success(asmsFaultAssetReasonService.selectAsmsFaultAssetReasonByFaultAssetReasonId(faultAssetReasonId));
    }

    /**
     * 新增资产故障原因
     */
    //   @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsFaultAssetReason:add")
    @Log(title = "资产故障原因", businessType = BusinessType.INSERT)
    @PostMapping("/addAsmsFaultAssetReason")
    @ApiOperation("新增资产故障原因")
    public AjaxResult add(@RequestBody AsmsFaultAssetReasonAddVo asmsFaultAssetReasonAddVo) {
        AsmsFaultAssetReason asmsFaultAssetReason = new AsmsFaultAssetReason();
        BeanUtils.copyProperties(asmsFaultAssetReasonAddVo, asmsFaultAssetReason);

        List<AsmsFaultAssetReason> list = asmsFaultAssetReasonService.list(new QueryWrapper<AsmsFaultAssetReason>().eq("asset_type_id", asmsFaultAssetReason.getAssetTypeId()).
                eq("fault_reason", asmsFaultAssetReason.getFaultReason()));

        if (list != null && list.size() > 0) {
            return AjaxResult.success("该故障已添加成功，请勿重复添加");
        }

        asmsFaultAssetReason.setCreateBy(SecurityUtils.getUsername());
        asmsFaultAssetReason.setCreateTime(System.currentTimeMillis());
        if (asmsFaultAssetReasonService.save(asmsFaultAssetReason)) {
            return AjaxResult.success("新增成功");
        } else {
            return AjaxResult.error("新增失败");
        }

    }

    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsFaultAssetReason:edit")
    @Log(title = "资产故障原因", businessType = BusinessType.UPDATE)
    @PostMapping("/editAsmsFaultAssetReason")
    @ApiOperation("修改资产故障原因")
    public AjaxResult editAsmsFaultAssetReason(@RequestBody AsmsFaultAssetReasonEditVo asmsFaultAssetReasonEditVo) {
        AsmsFaultAssetReason asmsFaultAssetReason = new AsmsFaultAssetReason();
        BeanUtils.copyProperties(asmsFaultAssetReasonEditVo, asmsFaultAssetReason);
        return toAjax(asmsFaultAssetReasonService.updateAsmsFaultAssetReason(asmsFaultAssetReason));
    }


    /**
     * 删除资产故障原因
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "asms:AsmsFaultAssetReason:remove")
    @Log(title = "资产故障原因", businessType = BusinessType.DELETE)
    @DeleteMapping("/{faultAssetReasonIds}")
    public AjaxResult remove(@PathVariable Long[] faultAssetReasonIds) {
        return toAjax(asmsFaultAssetReasonService.deleteAsmsFaultAssetReasonByFaultAssetReasonIds(faultAssetReasonIds));
    }

    @GetMapping("/getReasonListByTypeId")
    @ApiOperation("根据设备类型id获取设备故障原因列表")
    public AjaxResult getReasonListByTypeId(@ApiParam(name = "assetTypeId", value = "设备类型Id", required = true) Long assetTypeId) {
        R<AmsAssetType> rTypeInfo = assetTypeController.getInfo(assetTypeId);
        if (R.FAIL == rTypeInfo.getCode()) {
            throw new ServiceException(rTypeInfo.getMsg());
        }

        if (rTypeInfo.getData() == null) {
            return AjaxResult.success("找不到该故障");
        }
        Set<String> reason = new HashSet<>();
        List<AsmsFaultAssetReason> reasons = new ArrayList<>();
        String typeIdString = rTypeInfo.getData().getAncestors() + "," + assetTypeId;
        for (Long typeId : Convert.toLongArray(typeIdString)) {
            if (!typeId.equals(0L)) {
                List<AsmsFaultAssetReason> list = asmsFaultAssetReasonService.list(new QueryWrapper<AsmsFaultAssetReason>().eq(AsmsFaultAssetReason.ASSET_TYPE_ID, typeId));
                for (AsmsFaultAssetReason assetReason : list) {
                    if (!reason.contains(assetReason.getFaultReason())) {
                        reason.add(assetReason.getFaultReason());
                        reasons.add(assetReason);
                    }
                }
            }
        }

        return AjaxResult.success(reasons);
    }
}
